import { login, logout, getInfo, getRoutes } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  setName,
  setRoleName,
  removeName,
  removeRoleName,
  getName, getRoleName
} from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    roleName: '',
    avatar: '',
    routes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLE_NAME: (state, name) => {
    state.roleName = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  },
  RESET_ROUTES: (state) => {
    state.routes = []
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code, sessionId } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), password: password, code: code, sessionId: sessionId }).then(response => {
        // if (response.success && response.rCode == '200') {
        if (response.success) {
          commit('SET_TOKEN', response.resultData.access_token)
          commit('SET_NAME', response.resultData.name)
          commit('SET_ROLE_NAME', response.resultData.roleName)
        } else {
          this.$message({
            type: 'error',
            message: response.rMsg
          })
        }
        setToken(response.resultData.access_token)
        setName(response.resultData.name)
        setRoleName(response.resultData.roleName)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        // const { name, avatar } = data

        // commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      getRoutes().then(response => {
        const { resultData } = response
        if (!resultData) {
          return reject('身份验证失败，请重新登录')
        }
        commit('SET_ROUTES', resultData)
        resolve(resultData)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        // 清除动态加载的路由
        dispatch('permission/clearRouters', null, { root: true })
        // 清除获取到的原始路由菜单
        commit('RESET_ROUTES')
        // 清除路由
        resetRouter()
        removeName()
        removeRoleName()
        commit('RESET_STATE')
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit, state, dispatch }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      // 清除动态加载的路由
      dispatch('permission/clearRouters', null, { root: true })
      // 清除获取到的原始路由菜单
      commit('RESET_ROUTES')
      resetRouter()
      removeName()
      removeRoleName()
      commit('RESET_STATE')
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

